/*
参数说明：
alertShow-弹出框参数{
  showmsg-服务器弹窗提示
  msg-服务器提示内容
}
userData-用户基本信息{
  tel-手机号
  balance-账号余额
}
codeData-验证码基本信息参数{
  sendCode-控制是否出现验证倒计时标签
  time-倒计时时间
  userCode-验证码input框绑定数据
}
formData-页面基本信息参数{
  textType-是否显示输入金额大于账号余额文字提示的标签
  scole-选择积分抵扣了多少钱（初始化为‘已抵扣￥0.00>’）
  useNum-账号抵扣金额input框绑定数据
  money-选择积分抵扣返回之后获得的抵扣多少钱
  mianOrderId-订单Id
  useScore-使用了多少积分做抵扣
  inputTextMoney-微信需要支付的多少金额
  alltotal-订单总价
  orderbalance-话费多少钱最终余额
}
fnDataPrice-用于最终支付价格临时存储做删减用的参数(订单折扣后的总价-输入的余额val=最终微信需要支付的价格)
方法：
  getUserInfodata-取得用户手机号-账号余额
  buyGetData-取得订单数据
  moenyFn-控制是否显示输入金额大于账号余额
  setTime-验证码倒计时方法
  shopCleanfn-微信支付-同时先调用发送验证码到手机的接口
  codeTelFn-发送验证码信息
*/
<template>
  <div>
    <alert v-model="alertShow.showmsg" :title="'提示'" @on-show="onShow" @on-hide="onHide">{{alertShow.msg}}</alert>
    <x-header style="background-color:#3d82e5;width:100%;position:absolute;left:0;top:0;z-index:100;" :left-options="{showBack: false}">
      <p name="content">支付订单</p>
    </x-header>
    <group gutter="10" :title="''" style="padding-top: 18px">
      <cell :title="'订单总计'">
        <div slot="value">
          <h4 style="color: #fa1118">￥{{formData.alltotal}}</h4>
        </div>
      </cell>
      <!--<cell v-if="isVip==='false'" :title="'使用积分抵扣'" :value="formData.scole" @click.native="scroeFn" isLink></cell>-->
      <flexbox v-if="isVip==='false'"  :gutter="0" wrap="wrap" @click.native="scroeFn" style="background-color: #ffffff;padding-top: 10px;padding-bottom: 10px;border-top: 1px solid #D9D9D9">
        <flexbox-item :span="5">
          <p style="font-size: 13px;padding-left: 15px;color: #3d82e5">使用积分抵扣</p>
        </flexbox-item>
        <flexbox-item :span="6.7" style="text-align: right">
          <p style="font-size: 14px;color: #636363;display: inline-block">已抵扣</p>
          <p style="font-size: 14px;color: #3d82e5;display: inline-block">{{formData.scole}}</p>
          <p style="font-size: 14px;color: #636363;display: inline-block">&nbsp;〉</p>
        </flexbox-item>
      </flexbox>
    </group>
    <group :title="'余额支付'">
      <div style="font-size: 14px;padding-left: 15px;padding-top: 5px;padding-bottom: 5px">
        <p>当前账户余额：￥{{userData.balance}}</p>
      </div>
      <x-input title="" type="text" placeholder="请输入用余额支付的金额"  v-model="formData.useNum"  @on-change="moenyFn"></x-input>
    </group>
    <div v-if="formData.textType===true" style="padding-left: 15px;color: #f51313;">
      <p style="font-size: 14px;">输入的金额大于订单金额!</p>
    </div>
    <div v-if="formData.textType2===true" style="padding-left: 15px;color: #f51313;">
      <p style="font-size: 14px;">当前账户余额不足!</p>
    </div>
    <div v-if="formData.textType3===true" style="padding-left: 15px;color: #f51313;">
      <p style="font-size: 14px;">输入金额不正确!</p>
    </div>
    <flexbox :gutter="0"  wrap="nowrap" style="background-color: #ffffff;margin-top: 20px">
      <flexbox-item :span="5">
        <p style="padding-top: 10px;padding-bottom:10px;padding-left: 15px;font-size: 15px;color: #f51313">实付款</p>
      </flexbox-item>
      <flexbox-item :span="6.5">
        <p v-if="formData.textType3===true" style="padding-top: 10px;padding-bottom:10px;text-align: right;color: #f51313">￥0</p>
        <h4 v-if="formData.textType3===false" style="padding-top: 10px;padding-bottom:10px;text-align: right;color: #f51313">￥{{formData.inputTextMoney}}</h4>
      </flexbox-item>
    </flexbox>

    <div style="padding-left: 15px;padding-top: 10px;margin-top: 20px;">
      <p style="font-size: 14px;color: #636363 ">手机号码：{{userData.tel}}</p>
    </div>
    <group gutter="0">
      <x-input title="验证码" class="weui-vcode" placeholder="请输入验证码" v-model="codeData.userCode">
        <x-button v-if="codeData.sendCode===true" slot="right" style="background: #afafaf;position: absolute;right: 6px;top: 10px;padding: 0 3px" type="primary" mini>{{codeData.time}}S后重新发送</x-button>
      </x-input>
    </group>
    <div style="padding: 15px;margin-top: 20px;">
      <x-button v-if="formData.buttonType===true " disabled action-type="button" style="width: 200px;font-size: 15px;">{{buttionName}}</x-button>
      <x-button v-if="formData.buttonType===false" @click.native="shopCleanfn" style="font-size: 15px;width: 200px;background-color: #3d82e5;color: #ffffff">{{buttionName}}</x-button>
    </div>
    <div style="margin-top: 50px;text-align: center">
      <a :href="qqLink"><img src="../../../../assets/kefuButtion.png" width="90px"/></a>
    </div>
  </div>
</template>
<script>
  import { Group, Cell, Flexbox, FlexboxItem, XInput, Checklist, XButton, Alert, XHeader } from 'vux'
  import * as urls from '../../../../api/urls'
  import * as types from '../../../../store/types'
  import {API_ROOT} from '../../../../config.js'
  import $ from 'jquery'

  export default {
    components: {
      Group,
      Cell,
      FlexboxItem,
      Flexbox,
      XInput,
      Checklist,
      XButton,
      Alert,
      XHeader
    },
    mounted: function () {
      let qq = window.sessionStorage.getItem('sysqq')
      this.qqLink = 'http://wpa.qq.com/msgrd?v=3&uin=' + qq + '&site=qq&menu=yes'
      this.isVip = window.sessionStorage.getItem('isVip')
      this.formData.mianOrderId = window.sessionStorage.getItem('mianOrderId')
      this.formData.money = window.sessionStorage.getItem('money')
      this.formData.useScore = window.sessionStorage.getItem('useScore')
      this.buyGetData()
      this.getUserInfodata()
      this.weixinfn38()
    },
    data () {
      return {
        isVip: 'false',
        qqLink: '',
        alertShow: {
          showmsg: false,
          msg: ''
        },
        userData: {
          tel: '',
          balance: ''
        },
        codeData: {
          sendCode: false,
          time: 59,
          userCode: ''
        },
        buttionName: '发送验证码',
        formData: {
          textType: false,
          textType2: false,
          textType3: false,
          buttonType: false,
          scole: '￥0.00',
          useNum: '',
          money: '',
          useScore: '',
          mianOrderId: '',
          inputTextMoney: '',
          alltotal: '',
          orderbalance: ''
        },
        fnDataPrice: ''
      }
    },
    methods: {
      weixinfn38 () {
        let that = this
        let userId = window.sessionStorage.getItem('userId')
        let logo = window.sessionStorage.getItem('LOGO')
        let url = window.location.origin
        let link = url + '/api/wxAuth/index?type=t1' + '&uid=' + userId
        that.$wechat.onMenuShareAppMessage({
          title: '孝行通', // 分享标题
          desc: '孝行通·微商城 一个让子女为父母尽孝的老年服务平台', // 分享描述
          link: link, // 分享链接
          imgUrl: logo, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        })
        that.$wechat.onMenuShareTimeline({
          title: '孝行通', // 分享标题
          link: link, // 分享链接
          imgUrl: logo, // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        })
        $.ajax({
          url: API_ROOT + '/api/wxAuth/jsauth?url=' + encodeURIComponent(url + '/static/index.html'),
          type: 'post',
          success: function (t) {
            if (t.status === 100) {
              let sign = t.data.sign
              let weixinConfig38 = {
                debug: false,
                appId: sign.appId,
                timestamp: sign.timeStamp,
                nonceStr: sign.nonceStr,
                signature: sign.signature,
                jsApiList: ['onMenuShareAppMessage', 'chooseWXPay', 'onMenuShareTimeline']
              }
              // 授权
              that.$wechat.config(weixinConfig38)
              // 调用ready初始化
            } else {
              that.weixinfn38()
            }
          },
          error: function (t) {
            that.weixinfn38()
          }
        })
      },
      getUserInfodata () {
        let userId = window.sessionStorage.getItem('userId')
        let that = this
        this.http(urls.userIndex, {userId: userId}, function (res) {
          if (res.status === 100) {
            that.userData.tel = res.data.user.tel
            that.userData.balance = res.data.user.balance
          } else {
            that.alertShow.showmsg = true
            that.alertShow.msg = res.errMsg
          }
        }, function (res) {
          that.alertShow.showmsg = true
          that.alertShow.msg = res
        })
      },
      buyGetData () {
        let userId = window.sessionStorage.getItem('userId')
        let that = this
        this.http(urls.payDetail, {userId: userId, orderId: that.formData.mianOrderId}, function (res) {
          if (res.status === 100) {
            if (res.data !== null) {
              that.formData.alltotal = res.data.total
              that.formData.inputTextMoney = res.data.total
              that.fnDataPrice = res.data.total
              if (that.formData.money !== '') {
                that.formData.scole = '￥' + that.formData.money
                that.formData.inputTextMoney = that.formData.inputTextMoney - that.formData.money
                that.formData.inputTextMoney = Math.round(that.formData.inputTextMoney * 100) / 100
                that.fnDataPrice = that.formData.inputTextMoney
              } else {
                that.formData.scole = '￥0.00'
              }
            }
          } else {
            that.alertShow.showmsg = true
            that.alertShow.msg = res.errMsg
          }
        }, function (res) {
          that.alertShow.showmsg = true
          that.alertShow.msg = res
        })
      },
      moenyFn (val) {
        let that = this
        let textVal = val
        let alltotal = that.formData.alltotal
        let buyMoneyText = val * 100
        this.formData.orderbalance = textVal
        this.formData.textType = false
        this.formData.textType2 = false
        this.formData.textType3 = false
        this.formData.buttonType = false
        if (val === '') {
          that.formData.inputTextMoney = alltotal - that.formData.money
          that.formData.inputTextMoney = Math.round(that.formData.inputTextMoney * 100) / 100
        } else {
          if (parseInt(val) < 0) {
            this.formData.textType3 = true
            this.formData.buttonType = true
          } else {
            if (!buyMoneyText) {
              this.formData.textType3 = true
              this.formData.buttonType = true
            } else {
              if (textVal > this.userData.balance) {
                that.formData.textType2 = true
                that.formData.buttonType = true
              } else {
                if (that.fnDataPrice < textVal) {
                  that.formData.textType = true
                  that.formData.buttonType = true
                } else {
                  that.formData.inputTextMoney = that.fnDataPrice - textVal
                  that.formData.inputTextMoney = Math.round(that.formData.inputTextMoney * 100) / 100
                  that.formData.textType = false
                  that.formData.buttonType = false
                }
              }
            }
          }
        }
      },
      scroeFn () {
        let that = this
        window.sessionStorage.setItem('alltotal', that.formData.alltotal)
        this.$router.push({
          path: '/shoppingCar/SelectScore'
        })
        this.$router.go(1)
      },
      shopCleanfn () {
        let userId = window.sessionStorage.getItem('userId')
        let that = this
        if (this.codeData.userCode !== '') {
          // 余额付款
          that.http(urls.prePay, {userId: userId, orderId: that.formData.mianOrderId, orderPoint: that.formData.useScore, orderbalance: that.formData.orderbalance, code: that.codeData.userCode}, function (res) {
            if (res.status === 100) {
              if (res.data.paySuccess === true) {
                if (that.isVip === true) {
                  window.location.href = '/api/wxAuth/go/content+user+User'
                } else {
                  that.$store.commit(types.USER_ORDER, {index: 2})
                  that.$router.push({
                    path: '/order/OrderIndex'
                  })
                  that.$router.go(1)
                }
              } else {
                let that2D = that
                if (that.isVip === true) {
                  that.$wechat.chooseWXPay({
                    'appId': res.data.data.appId,
                    'timestamp': res.data.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    'nonceStr': res.data.data.nonceStr, // 支付签名随机串，不长于 32 位
                    'package': res.data.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    'signType': 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    'paySign': res.data.data.sign, // 支付签名
                    success: function (res) {
                      // 支付成功后的回调函数
                      if (res.errMsg === 'chooseWXPay:ok') {
                        that2D.http(urls.sarch, { userId: userId, orderId: that2D.formData.mianOrderId }, function (res) {
                          if (res.status === 100) {
                            window.location.href = '/api/wxAuth/go/content+user+User'
                          } else {
                            that2D.alertShow.showmsg = true
                            that2D.alertShow.msg = res.errMsg
                          }
                        }, function (res) {
                          that2D.alertShow.showmsg = true
                          that2D.alertShow.msg = res
                        })
                      }
                    }
                  })
                } else {
                  that.$wechat.chooseWXPay({
                    'appId': res.data.data.appId,
                    'timestamp': res.data.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    'nonceStr': res.data.data.nonceStr, // 支付签名随机串，不长于 32 位
                    'package': res.data.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    'signType': 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    'paySign': res.data.data.sign, // 支付签名
                    success: function (res) {
                      // 支付成功后的回调函数
                      if (res.errMsg === 'chooseWXPay:ok') {
                        that2D.http(urls.sarch, { userId: userId, orderId: that2D.formData.mianOrderId }, function (res) {
                          if (res.status === 100) {
                            that2D.$store.commit(types.USER_ORDER, {index: 2})
                            that2D.$router.push({
                              path: '/order/OrderIndex'
                            })
                            that2D.$router.go(1)
                          } else {
                            that2D.alertShow.showmsg = true
                            that2D.alertShow.msg = res.errMsg
                          }
                        }, function (res) {
                          that2D.alertShow.showmsg = true
                          that2D.alertShow.msg = res
                        })
                      }
                    }
                  })
                }
              }
            } else {
              that.codeData.userCode = ''
              that.buttionName = '发送验证码'
              that.alertShow.showmsg = true
              that.alertShow.msg = res.errMsg
            }
          }, function (res) {
            that.alertShow.showmsg = true
            that.alertShow.msg = res
          })
        } else {
          that.$vux.confirm.show({
            title: '提示',
            content: '是否发送验证码到绑定手机',
            confirmText: '发送',
            // 组件除show外的属性
            onConfirm () {
              if (that.codeData.time === 59) {
                that.buttionName = '确认支付'
                that.codeTelFn()
              } else {
                that.alertShow.showmsg = true
                that.alertShow.msg = '请在' + that.codeData.time + 'S后点击发送新的验证码,如果已收到请填写验证码'
              }
            }
          })
        }
      },
      codeTelFn () {
        let userId = window.sessionStorage.getItem('userId')
        let that = this
        that.http(urls.payMessage, {userId: userId}, function (res) {
          if (res.status === 100) {
            that.alertShow.showmsg = true
            that.alertShow.msg = '验证码已发出，请注意手机查收'
            that.codeData.sendCode = true
            that.setTime()
          } else {
            that.alertShow.showmsg = true
            that.alertShow.msg = res.errMsg
          }
        }, function (res) {
          that.alertShow.showmsg = true
          that.alertShow.msg = res
        })
      },
      setTime () {
        let interval
        let that = this
        let setTimeFn = function () {
          that.codeData.time--
          if (that.codeData.time < 0) {
            clearInterval(interval)
            that.codeData.sendCode = false
            that.codeData.time = 59
          }
        }
        interval = setInterval(function () {
          setTimeFn()
        }, 1000)
      },
      onShow () {
        // 弹窗出现时触发
      },
      onHide () {
        // 弹窗关闭时触发
      }
    }
  }
</script>
<style scoped="scoped">
</style>
